<template>
  <div class="user-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-button @click="$router.back()" :icon="ArrowLeft">返回</el-button>
      <h1 class="page-title">用户详情</h1>
    </div>

    <div v-loading="loading" class="detail-container">
      <!-- 基本信息 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit"
              v-if="userInfo && userInfo.status !== 'banned'"
            >
              编辑
            </el-button>
          </div>
        </template>
        
        <div v-if="userInfo" class="user-info-content">
          <div class="avatar-section">
            <el-avatar :size="120" :src="userInfo.avatar">
              {{ userInfo.nickname?.charAt(0) }}
            </el-avatar>
            <div class="status-badges">
              <el-tag 
                :type="userInfo.status === 'active' ? 'success' : userInfo.status === 'banned' ? 'danger' : 'warning'"
                size="large"
              >
                {{ getStatusText(userInfo.status) }}
              </el-tag>
              <el-tag type="info" size="large">
                {{ getRoleText(userInfo.role) }}
              </el-tag>
            </div>
          </div>

          <div class="info-grid">
            <div class="info-item">
              <label>用户ID：</label>
              <span>{{ userInfo.id }}</span>
            </div>
            <div class="info-item">
              <label>昵称：</label>
              <span>{{ userInfo.nickname || '-' }}</span>
            </div>
            <div class="info-item">
              <label>手机号：</label>
              <span>{{ userInfo.phone || '未绑定' }}</span>
            </div>
            <div class="info-item">
              <label>邮箱：</label>
              <span>{{ userInfo.email || '未绑定' }}</span>
            </div>
            <div class="info-item">
              <label>性别：</label>
              <span>{{ getGenderText(userInfo.gender) }}</span>
            </div>
            <div class="info-item">
              <label>生日：</label>
              <span>{{ userInfo.birthday ? formatDate(userInfo.birthday) : '-' }}</span>
            </div>
            <div class="info-item">
              <label>城市：</label>
              <span>{{ userInfo.city || '-' }}</span>
            </div>
            <div class="info-item">
              <label>积分：</label>
              <span class="highlight">{{ userInfo.points || 0 }}</span>
            </div>
            <div class="info-item">
              <label>等级：</label>
              <span class="highlight">Lv.{{ userInfo.level || 1 }}</span>
            </div>
            <div class="info-item">
              <label>注册时间：</label>
              <span>{{ formatDateTime(userInfo.createdAt) }}</span>
            </div>
            <div class="info-item">
              <label>最后登录：</label>
              <span>{{ userInfo.lastLoginAt ? formatDateTime(userInfo.lastLoginAt) : '从未登录' }}</span>
            </div>
            <div class="info-item full-width" v-if="userInfo.bio">
              <label>个人简介：</label>
              <span>{{ userInfo.bio }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 统计信息 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-item">
              <el-icon :size="40" color="#409eff"><Calendar /></el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ stats.eventCount || 0 }}</div>
                <div class="stat-label">参与活动</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-item">
              <el-icon :size="40" color="#67c23a"><UserFilled /></el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ stats.clubCount || 0 }}</div>
                <div class="stat-label">加入俱乐部</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-item">
              <el-icon :size="40" color="#e6a23c"><Star /></el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ stats.favoriteCount || 0 }}</div>
                <div class="stat-label">收藏场地</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-item">
              <el-icon :size="40" color="#f56c6c"><ChatDotRound /></el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ stats.commentCount || 0 }}</div>
                <div class="stat-label">发布评论</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 活动记录 -->
      <el-card class="activity-card">
        <template #header>
          <span>最近活动记录</span>
        </template>
        <el-table :data="activities" style="width: 100%">
          <el-table-column prop="eventName" label="活动名称" />
          <el-table-column prop="eventTime" label="活动时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.eventTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getEventStatusType(row.status)" size="small">
                {{ getEventStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="joinTime" label="报名时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.joinTime) }}
            </template>
          </el-table-column>
        </el-table>
        <div v-if="activities.length === 0" class="empty-text">
          暂无活动记录
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <el-card class="action-card">
        <template #header>
          <span>操作</span>
        </template>
        <el-space wrap>
          <el-button 
            v-if="userInfo?.status === 'active'"
            type="warning" 
            @click="handleBan"
          >
            <el-icon><Lock /></el-icon>
            封禁用户
          </el-button>
          <el-button 
            v-if="userInfo?.status === 'banned'"
            type="success" 
            @click="handleUnban"
          >
            <el-icon><Unlock /></el-icon>
            解除封禁
          </el-button>
          <el-button type="info" @click="handleResetPassword">
            <el-icon><Key /></el-icon>
            重置密码
          </el-button>
          <el-button type="primary" @click="handleViewEvents">
            <el-icon><Calendar /></el-icon>
            查看全部活动
          </el-button>
        </el-space>
      </el-card>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户信息"
      width="600px"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="城市">
          <el-input v-model="editForm.city" />
        </el-form-item>
        <el-form-item label="积分">
          <el-input-number v-model="editForm.points" :min="0" />
        </el-form-item>
        <el-form-item label="等级">
          <el-input-number v-model="editForm.level" :min="1" :max="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const saving = ref(false)
const userInfo = ref(null)
const stats = ref({})
const activities = ref([])
const editDialogVisible = ref(false)
const editForm = ref({})

const userId = route.params.id

// 加载用户详情
const loadUserDetail = async () => {
  loading.value = true
  try {
    const res = await userApi.getUserDetail(userId)
    userInfo.value = res.data
    
    // 加载统计数据（模拟数据，实际应该调用API）
    stats.value = {
      eventCount: 15,
      clubCount: 3,
      favoriteCount: 8,
      commentCount: 42
    }
    
    // 加载最近活动（模拟数据）
    activities.value = [
      {
        eventName: '周末足球赛',
        eventTime: '2025-10-15 14:00:00',
        status: 'joined',
        joinTime: '2025-10-10 10:30:00'
      },
      {
        eventName: '篮球友谊赛',
        eventTime: '2025-10-08 16:00:00',
        status: 'completed',
        joinTime: '2025-10-05 15:20:00'
      }
    ]
  } catch (error) {
    ElMessage.error('加载用户详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 编辑用户
const handleEdit = () => {
  editForm.value = { ...userInfo.value }
  editDialogVisible.value = true
}

// 保存编辑
const handleSaveEdit = async () => {
  saving.value = true
  try {
    await userApi.updateUser(userId, editForm.value)
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    loadUserDetail()
  } catch (error) {
    ElMessage.error('更新失败')
    console.error(error)
  } finally {
    saving.value = false
  }
}

// 封禁用户
const handleBan = async () => {
  try {
    await ElMessageBox.confirm('确定要封禁该用户吗？', '警告', {
      type: 'warning'
    })
    await userApi.banUser(userId)
    ElMessage.success('封禁成功')
    loadUserDetail()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 解除封禁
const handleUnban = async () => {
  try {
    await ElMessageBox.confirm('确定要解除封禁吗？', '提示', {
      type: 'info'
    })
    await userApi.unbanUser(userId)
    ElMessage.success('已解除封禁')
    loadUserDetail()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 重置密码
const handleResetPassword = async () => {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
      type: 'warning'
    })
    // TODO: 调用重置密码API
    ElMessage.success('密码已重置为默认密码')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 查看全部活动
const handleViewEvents = () => {
  // TODO: 跳转到用户的活动列表页面
  ElMessage.info('功能开发中')
}

// 格式化函数
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : '-'
}

const formatDateTime = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

const getStatusText = (status) => {
  const map = {
    'active': '正常',
    'inactive': '未激活',
    'banned': '已封禁'
  }
  return map[status] || status
}

const getRoleText = (role) => {
  const map = {
    'customer': '运动客户',
    'venue_manager': '场地管理员',
    'admin': '系统管理员'
  }
  return map[role] || role
}

const getGenderText = (gender) => {
  const map = {
    'male': '男',
    'female': '女',
    'other': '其他'
  }
  return map[gender] || '未设置'
}

const getEventStatusType = (status) => {
  const map = {
    'joined': 'primary',
    'completed': 'success',
    'cancelled': 'info'
  }
  return map[status] || 'info'
}

const getEventStatusText = (status) => {
  const map = {
    'joined': '已报名',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return map[status] || status
}

onMounted(() => {
  loadUserDetail()
})
</script>

<style scoped lang="scss">
.user-detail {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    margin: 0;
  }
}

.detail-container {
  .info-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .user-info-content {
      .avatar-section {
        display: flex;
        align-items: center;
        gap: 30px;
        margin-bottom: 30px;
        padding-bottom: 30px;
        border-bottom: 1px solid #ebeef5;

        .status-badges {
          display: flex;
          gap: 10px;
        }
      }

      .info-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 20px;

        .info-item {
          display: flex;
          align-items: center;

          &.full-width {
            grid-column: 1 / -1;
            flex-direction: column;
            align-items: flex-start;
          }

          label {
            font-weight: 500;
            color: #606266;
            margin-right: 10px;
            min-width: 80px;
          }

          span {
            color: #303133;

            &.highlight {
              color: #409eff;
              font-weight: 600;
              font-size: 16px;
            }
          }
        }
      }
    }
  }

  .stats-row {
    margin-bottom: 20px;

    .stat-item {
      display: flex;
      align-items: center;
      gap: 15px;

      .stat-info {
        .stat-value {
          font-size: 28px;
          font-weight: bold;
          color: #303133;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-top: 5px;
        }
      }
    }
  }

  .activity-card {
    margin-bottom: 20px;

    .empty-text {
      text-align: center;
      color: #909399;
      padding: 40px 0;
    }
  }

  .action-card {
    margin-bottom: 20px;
  }
}
</style>
